package org.ezplatform.office.forum.web.rest;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.role.RoleApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.security.SecurityUtils;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.forum.entity.ForumBoard;
import org.ezplatform.office.forum.entity.ForumPost;
import org.ezplatform.office.forum.service.ForumBoardService;
import org.ezplatform.office.forum.service.ForumPostService;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;

/**
 * 板块管理控制类
 * 2019年11月2日17:40:59
 * @author Administrator
 *
 */
@RestController
@RequestMapping(value = "/api/w/forum/board")
public class ForumBoardWebApiController extends BaseController<ForumBoard, String>{
	
    private final Logger LOGGER = LoggerFactory.getLogger(ForumBoardWebApiController.class);

    @Autowired
    private ForumBoardService forumBoardService;
    
	@Autowired
	private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
	private RoleApiService roleApiService;
	
	@Autowired
	private AttachmentUtilsService attachmentUtilsService;

	@Autowired
    private UserApiService userApiService;
	
	@Autowired
	private ForumPostService forumPostService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
    private RestClient restClient;
	
    @Override
    protected BaseService<ForumBoard, String> getEntityService() {
        return forumBoardService;
    }
	    
    /**
     * 初始化数据
     *
     * @param request
     * @param model
     * @param id
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,@RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }
	    
    /**
     * 获取版块列表数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions({"stdForum:board:03"})
    public Page<Map> findByPage(HttpServletRequest request) {
        String corpId = WebUtils.getCurrentUser().getCorpId();
        String typeId = request.getParameter("typeId");
        //获取翻页对象
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		//获取查询条件对象
		List<PropertyFilter> filter = PropertyFilter.buildFiltersFromHttpRequest(ForumBoard.class, request);
		Page<Map> page = forumBoardService.findPage(pageable, filter, TOKEN, corpId,typeId);
        return page;
    }
    
  /**
   * 根据id获取版块信息
   * @param id
   * @param request
   * @return
   */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions(value = {"stdForum:board:03", "stdForum:board:02"}, logical = Logical.OR)
    public OperationResult editShow(@RequestParam("id") String id,HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String logStatus = request.getParameter("logStatus");
        ForumBoard b = forumBoardService.findOne(id);
        Map m = null;
        try {
            m = BeanUtils.describe(b);
            //获取版主
            String moderatorStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(b.getId()));
            //获取适用范围
            String aplicationStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "aplication_scope", StringUtils.null2String(b.getAplicationScope()));
            //获取黑名单
            String userStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", StringUtils.null2String(b.getId()));
            m.put("aplicationStr", aplicationStr);
            m.put("moderatorStr", moderatorStr);
            m.put("userStr", userStr);
            int sendPost = forumBoardService.getPostNum(b.getId(),"1",WebUtils.getCurrentUser().getCorpId());
            m.put("sendPostNum", sendPost);
            int rePost = forumBoardService.getPostNum(b.getId(),"2",WebUtils.getCurrentUser().getCorpId());
            m.put("rePostNum", rePost);
            if(logService.checkOptLog("0", "forum:board:03", user.getJwtToken())) {
            	if(!StringUtils.equals(logStatus, "1")) {
                	logService.saveModuleLog("forum:board:03", b.getName(), ""); 
                }
            }
            String attIdJson = getAttachmentFile(m.get("attId"), user.getJwtToken());
            m.put("attIdJson", attIdJson);
        } catch (IllegalAccessException e) {
            LOGGER.error(e.getMessage());
        } catch (NoSuchMethodException e) {
            LOGGER.error(e.getMessage());
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return OperationResult.buildSuccessResult(m);
    }
    
    /**
     * 保存/修改版块信息
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions(value = {"stdForum:board:01", "stdForum:board:02"}, logical = Logical.OR)
    public OperationResult editSave(@ModelAttribute("entity") ForumBoard entity, HttpServletRequest request, Model model) {
    	OperationResult result;
    	String code = entity.getCode();
    	String corpId = WebUtils.getCurrentUser().getCorpId();
    	String usersIcon = request.getParameter("usersIcon1");
    	entity.setModerator(usersIcon);
    	if(!forumBoardService.checkCodeUnique(entity.getId(),code,corpId)){
	    	String moderatorJsonStr = request.getParameter("moderatorJsonStr");
	    	String userJsonStr = request.getParameter("userJsonStr");
	    	String aplicationJsonStr = request.getParameter("aplicationJsonStr");
	    	if(!ValidateUtils.validateChar(userJsonStr, "%+")){
	    		return OperationResult.buildFailureResult("非法参数!");
			  }
	    	if(!ValidateUtils.validateInt(String.valueOf(entity.getIsCheck())) ){
	    		return OperationResult.buildFailureResult("非法参数!");
			  }
	    	if(!ValidateUtils.validateInt(String.valueOf(entity.getSortNo())) ){
	    		return OperationResult.buildFailureResult("非法参数!");
			  }
	    	if(!ValidateUtils.validateInt(String.valueOf(entity.getIsNavigation())) ){
	    		return OperationResult.buildFailureResult("非法参数!");
			  }
	    	if(!ValidateUtils.validateChar(entity.getDescription(), "%+")){
	    		return OperationResult.buildFailureResult("+、%是非法参数，禁止输入!");
			  }
	    	/*if(entity.getIsNavigation()==1) {
	    		if(!forumBoardService.checkRecommendTime(entity.getId())||StringUtils.isBlank(entity.getId())) {
	    			entity.setRecommendTime(new Date());
	    		}
	    	}*/
	    	boolean isAdd = false;
	    	if(StringUtils.isBlank(entity.getId())) {
	    		isAdd= true;
	    	}
	    	//生成适用范围
	    	if(StringUtils.isEmpty(entity.getAplicationScope())) {
	    		entity.setAplicationScope(UuidUtils.UUID());
	    	}
	    	result = super.editSave(entity);
	    	WebUser user = WebUtils.getCurrentUser();
	    	//保存后id生成了值
            popUserScopeUtilService.saveScopeData("oa_forum_moderator_scope",entity.getId(), moderatorJsonStr, "oa_forum_board", "id");
            popUserScopeUtilService.saveScopeData("oa_forum_board_user_scope",entity.getId(), userJsonStr, "oa_forum_board", "id");
            popUserScopeUtilService.saveScopeData("oa_forum_board_user_scope",entity.getAplicationScope(), aplicationJsonStr, "oa_forum_board", "aplication_scope");
	    	//forumBoardService.updateModerator(getToken(), entity.getId());
	    	if(isAdd) {
	    		if(logService.checkOptLog("0", "forum:board:01", user.getJwtToken())) {
	    			logService.saveModuleLog("forum:board:01", entity.getName(), ""); 
	    		}
	    	}else {
	    		ForumBoard oldBoard = forumBoardService.findOne(entity.getId());
	    		if(logService.checkOptLog("0", "forum:board:02", user.getJwtToken())) {
	    			logService.saveModuleLog("forum:board:02", oldBoard.getName(), ""); 
	    		}
	    	}
    	} else {
    		Map resources = new HashMap();
    		//国际化资源
            resources.put("i18NCode", "oa.forum.tips2");
            result = OperationResult.buildFailureResult("您输入的版块编码已存在",resources);
    		//result = new OperationResult(OperationResult.OPERATION_RESULT_TYPE.failure, "您输入的版块编码已存在");
    	}
        return result;
    }
    
    /**
     * 批量删除数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions({"stdForum:board:04"})
    public OperationResult delete(@RequestParam("ids") String... ids) {
        return forumBoardService.logicDelete(ids);
    }
	    
    /**
     * 删除一个数据
     */
    @RequestMapping(value = "/deleteOne", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions({"stdForum:board:04"})
    public OperationResult deleteOne(@RequestParam("ids") String... id) {
    	return forumBoardService.logicDeleteOne(id);
    }
	    
    /**
     * 根据id获取信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions({"stdForum:board:03"})
    public OperationResult viewShow(@RequestParam("id") String id) {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	String token = user.getJwtToken();
        Map result = forumBoardService.viewBoard(id);
        if(result != null && result.size() >0) {
        	 String moderatorStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(id));
             String userStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", StringUtils.null2String(id));
             String aplicationStr = "";
             if(StringUtils.isNotEmpty(StringUtils.null2String(result.get("aplicationScope")))) {
            	 aplicationStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "aplication_scope", StringUtils.null2String(result.get("aplicationScope")));
             }
             String attIdJson = getAttachmentFile(result.get("attId"), user.getJwtToken());
             result.put("attIdJson", attIdJson);
             result.put("moderatorStr", moderatorStr);
             result.put("userStr", userStr);
             result.put("aplicationStr", aplicationStr);
             StringBuffer moderatorNameStr = new StringBuffer();
             String[] moderatorIds =  moderatorStr.split(",");
             for(String moderatorId : moderatorIds) {
            	//如果是user
             	if(moderatorId.contains("user")) {
             		Map moderatorIdName = forumPostService.findUserName(moderatorId.substring(9));
                  	if(moderatorIdName != null) {
                  		moderatorNameStr.append(moderatorIdName.get("user_name")+" ") ;
                  	}
             	}else {//为组织
             		 String name = userApiService.getScopeName(moderatorId,corpId,token);
             		 if(StringUtils.isNotEmpty(name)) {
             			moderatorNameStr.append(name+" ") ;
             		 }
             	}
             }
             StringBuffer applicationNameStr = new StringBuffer();
             String[] applicationIds =  aplicationStr.split(",");
             for(String aplicationId : applicationIds) {
            	//如果是user
              	if(aplicationId.contains("user")) {
              		Map aplicationIdName = forumPostService.findUserName(aplicationId.substring(9));
                   	if(aplicationIdName != null) {
                   		applicationNameStr.append(aplicationIdName.get("user_name")+" ") ;
                   	}
              	}else {//为组织
              		 String name = userApiService.getScopeName(aplicationId,corpId,token);
              		 if(StringUtils.isNotEmpty(name)) {
              			applicationNameStr.append(name+" ") ;
              		 }
              	}
             }
             StringBuffer userNameStr = new StringBuffer();
             if(StringUtils.isNotEmpty(userStr)) {
             	 String[] userNameIds =  userStr.split(",");
                  for(String userNameId : userNameIds) {
                	//如果是user
                	if(userNameId.contains("user")) {
                		Map userName = forumPostService.findUserName(userNameId.substring(9));
                     	if(userName != null) {
                     		userNameStr.append(userName.get("user_name")+" ") ;
                     	}
                	}else {//为组织
                		 String name = userApiService.getScopeName(userNameId,corpId,token);
                		 if(StringUtils.isNotEmpty(name)) {
                			 userNameStr.append(name+" ") ;
                		 }
                	}
                  }
             }
             result.put("moderatorNameStr", moderatorNameStr.toString());
             result.put("applicationNameStr", applicationNameStr.toString());
             result.put("userNameStr", userNameStr.toString());
             if(logService.checkOptLog("0", "forum:board:03", user.getJwtToken())) {
             	 logService.saveModuleLog("forum:board:03", result.get("name").toString(), ""); 
             }
        }
        return OperationResult.buildSuccessResult(result);
    }
	    
   /**
    * 版块导航页面获取类别-版块信息
    * @param request
    * @return
    */
    @RequestMapping(value = "/findNavigation", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult findForumNavigation(HttpServletRequest request){
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	List<Map> list = forumBoardService.findForumNavigation(corpId, user.getJwtToken(), user);
    	return OperationResult.buildSuccessResult(list);
    }
    
    /**
     * 版主版块导航页面获取类别-版块信息
     * @param request
     * @return
     */
     @RequestMapping(value = "/findMDNavigation", method = RequestMethod.GET)
     @ResponseBody
     public OperationResult findMDForumNavigation(HttpServletRequest request){
     	WebUser user = WebUtils.getCurrentUser();
     	String corpId = user.getCorpId();
     	List<Map> list = forumBoardService.findMDForumNavigation(corpId, user.getJwtToken(), user);
     	return OperationResult.buildSuccessResult(list);
     }
	    
    /**
     * 版块导航
     * @param request
     * @return
     */
    @RequestMapping(value = "/findNavigationInfo", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult findNavigationInfo(HttpServletRequest request){
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	String boardId = request.getParameter("boardId");
    	Map<String,Object> map = forumBoardService.findNavigationInfo(boardId,corpId, user.getJwtToken());
    	return OperationResult.buildSuccessResult(map);
    }
	    
   /**
    * 获取类别-版块树
    * @param request
    * @return
    */
    @RequestMapping(value = "/getTypeBoardTree", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getTypeBoardTree(HttpServletRequest request){
    	WebUser user = WebUtils.getCurrentUser();
        String name = ValidateUtils.filter(request.getParameter("name"));
        String withoutBoard = request.getParameter("withoutBoard");
        //1.查类别下的版块 2.不查类别下的版块
    	List<Map> list = forumBoardService.getTypeBoardTree(name, user.getCorpId(),withoutBoard,user);
    	return OperationResult.buildSuccessResult(list);
    }
    
    /**
     * 获取版主类别-版块树
     * @param request
     * @return
     */
     @RequestMapping(value = "/getMDTypeBoardTree", method = RequestMethod.GET)
     @ResponseBody
     public OperationResult getMDTypeBoardTree(HttpServletRequest request){
     	WebUser user = WebUtils.getCurrentUser();
         String name = ValidateUtils.filter(request.getParameter("name"));
         String withoutBoard = request.getParameter("withoutBoard");
         //1.查版主类别下的版块 2.不查类别下的版块
     	List<Map> list = forumBoardService.getMDTypeBoardTree(name, user.getCorpId(),withoutBoard,user);
     	return OperationResult.buildSuccessResult(list);
     }
	    
    /**
     * 查询板块下是否有审核中的帖子和审核通过的帖子
     * @param request
     * @return
     */
    @RequestMapping(value = "/ifDelete", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions({"stdForum:forumCate:04"})
    public OperationResult ifDelete(HttpServletRequest request) {
    	String id = request.getParameter("id");
    	Map<String,String> data = new HashMap();
    	//查询有无审核中和审核通过的帖子
    	data = forumBoardService.ifDelete(id);
    	return OperationResult.buildSuccessResult(data);
    }
	   
    @RequestMapping(value = "/getBoardModeratorInfo", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getBoardModeratorInfo(@RequestParam("id") String paramId){
    	String id =ValidateUtils.filter(paramId);
        Map m = new HashMap();
        m = forumBoardService.getBoardModeratorInfoById(TOKEN, id);
        WebUser user = WebUtils.getCurrentUser();
        // 判断当前用户是否有该版块的发帖权限；
        List list = forumBoardService.postBoards1(TOKEN, user.getUserId(), user.getCorpId(), user.getUserName(),user.getRoleCodes());
        Iterator it = list.iterator();
        boolean postPermission = false;
        while(it.hasNext()){
            Map sm = (Map)it.next();
            if(StringUtils.equals(StringUtils.null2String(sm.get("id")), id)){
                postPermission = true;
            }
        }
        if( postPermission || SecurityUtils.isSuperAdmin(user)||user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())){
            m.put("postPermission", true);
        } else {
            m.put("postPermission", false);
        }
        //判断是不是管理员权限和超级管理员
        boolean flag = forumBoardService.checkBoardAuthor(TOKEN, user.getUserId(), user.getCorpId(),id);
        if( flag || SecurityUtils.isSuperAdmin(user)||user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())){
            m.put("isAdmin", true);
        } else {
            m.put("isAdmin", false);
        }
        List<Map<String,Object>> list1=  roleApiService.getRolesByUserId(user.getUserId(), user.getCorpId(), user.getJwtToken());
        List<String> list2 = new ArrayList();
		if(list1.size()>0) {
			for(Map<String,Object> map:list1) {
				if(map.get("roleCode") !="" && map.get("roleCode")!=null) {
					list2.add(StringUtils.null2String(map.get("roleCode")) );
				}	
			}
		}
		boolean boardAdmin = list2.contains("appAdminRole")||list2.contains("sysAdminRole")||user.getUserId().equals("1");
		m.put("boardAdmin",boardAdmin);
        // 判断当前用户是否是版主or超级管理员
        if(forumBoardService.IsModeratorOfBoard(id) || SecurityUtils.isSuperAdmin(user)){
            m.put("permission", true);
        } else {
            m.put("permission", false);
        }

        return OperationResult.buildSuccessResult(m) ;

    }
    
    /**
     * 查询用户是否有昵称
     * @param request
     * @return
     */
    @RequestMapping(value = "/ifPetname", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult ifPetname(HttpServletRequest request) {
    	//取用户个性签名、昵称
    	WebUser webUser = WebUtils.getCurrentUser();
    	String userId = webUser.getUserId();
    	Map<String, String> textParams = Maps.newHashMap();
    	textParams.put("userId", userId);
		textParams.put("corpId", webUser.getCorpId());
		String jsonStr = this.restClient.get("/portal/setting/userinfo/getUserExt", webUser.getJwtToken(), textParams);
		Map<String, Object> result = JsonUtils.readValue(jsonStr);
		result = JsonUtils.readValue(jsonStr);
		String petName ="";
		if("0".equals(StringUtils.null2String(result.get("code")))){
			if(result.get("data")!=null) {
				Map<String, Object> userExtMap = Maps.newHashMap();
				userExtMap = (Map<String, Object>) result.get("data");
				petName = StringUtils.null2String(userExtMap.get("petName"));
			}
		}
		Map<String,String> data = new HashMap();
		data.put("petName", petName);
    	return OperationResult.buildSuccessResult(data);
    }
	    
    /**
	 * 获取附件信息
	 * @param attId
	 * @param token
	 * @return
	 */
	public String getAttachmentFile(Object attId, String token) {
		String attachment = StringUtils.null2String(attId);
		StringBuffer file = new StringBuffer();
		if (!"".equals(attachment)) {
			String result = attachmentUtilsService.getAttachmentInfo(attachment, token);
			file.append("[").append(result).append("]");
		}
		return file.toString();
	}
}